package com.iteaj.iot.test.mqtt;

import cn.hutool.json.JSONUtil;
import com.iteaj.iot.client.protocol.ClientInitiativeProtocol;
import com.iteaj.iot.message.DefaultMessageHead;
import com.iteaj.iot.test.ClientSnGen;
import com.iteaj.iot.test.TestStatus;
import com.iteaj.iot.test.TestStatusHeader;
import com.iteaj.iot.test.TestProtocolType;
import io.netty.handler.codec.mqtt.MqttQoS;

import java.nio.charset.StandardCharsets;

/**
 * create time: 2021/9/3
 *  客户端主动请求Mqtt Broker请求协议
 * @author iteaj
 * @since 1.0
 */
public class MqttPublishTestProtocol extends ClientInitiativeProtocol<MqttClientTestMessage> {

    private MqttQoS qoS;
    private String topic;

    public MqttPublishTestProtocol(String topic) {
        this(MqttQoS.AT_MOST_ONCE, topic);
    }

    public MqttPublishTestProtocol(MqttQoS qoS, String topic) {
        this.qoS = qoS;
        this.topic = topic;
    }

    @Override
    protected MqttClientTestMessage doBuildRequestMessage() {
        DefaultMessageHead messageHead = new DefaultMessageHead("MqttTestSn", ClientSnGen.getMessageId(), protocolType());

        // 测试平台主动
        if("broker".equals(this.topic)) {
            messageHead = new TestStatusHeader("MqttTestStatus"
                    , messageHead.getMessageId(), TestProtocolType.PIReq, TestStatus.开启);
        }

        messageHead.setMessage(JSONUtil.toJsonStr(messageHead).getBytes(StandardCharsets.UTF_8));
        return new MqttClientTestMessage(messageHead, this.qoS, this.topic);
    }

    @Override
    public void doBuildResponseMessage(MqttClientTestMessage responseMessage) {

    }

    @Override
    public TestProtocolType protocolType() {
        return TestProtocolType.CIReq;
    }

    public String getTopic() {
        return topic;
    }
}
